package source

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"init-database/model"
	"init-database/service"
)

type initUser struct{}

const initOrderUser = service.InitOrderSystem + 1

// auto run
func init() {
	service.RegisterInit(initOrderUser, &initUser{})
}

func (i *initUser) TableCreated(ctx context.Context) bool {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return false
	}
	return db.Migrator().HasTable(&model.SysMenu{})
}

func (i *initUser) MigrateTable(ctx context.Context) (context.Context, error) {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return ctx, errors.New("missing db in context")
	}
	return ctx, db.AutoMigrate(&model.SysUser{})
}

func (i initUser) InitializerName() string {
	return model.SysUser{}.TableName()
}

func (i *initUser) InitializerData(ctx context.Context) (next context.Context, err error) {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return nil, errors.New("missing db in context")
	}

	entities := model.SysUser{}.GetInitData()
	if err = db.Create(&entities).Error; err != nil {
		return ctx, errors.New(model.SysUser{}.TableName() + "表数据初始化失败!")
	}
	next = context.WithValue(ctx, i.InitializerName(), entities)

	return next, nil
}

func (i *initUser) DataInserted(ctx context.Context) bool {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return false
	}
	var record model.SysUser
	if errors.Is(db.Where("username = ?", "a303176530").First(&record).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
		return false
	}
	return record.AuthorityId == 9528
}
